package com.gouqi.tools.filter;

import com.gouqi.tools.common.ErrorCode;
import com.gouqi.tools.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class VerifyCodeFilter extends GenericFilterBean {

	private final String defaultFilterProcessUrl = "/api/user/login";

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
			// 验证码验证
			String requestCaptcha = request.getParameter("code");
			String genCaptcha = (String) request.getSession().getAttribute("code");
			if (StringUtils.isEmpty(requestCaptcha))
				throw new BusinessException(ErrorCode.PARAMS_ERROR, "验证码不能为空!");
			if (!genCaptcha.toLowerCase().equals(requestCaptcha.toLowerCase())) {
				throw new BusinessException(ErrorCode.PARAMS_ERROR, "验证码错误!");
			}
		}
		chain.doFilter(request, response);
	}

}
